﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace ExpertNewsRotator2
{
    public class ImageUploaderControl : TextField
    {
        private ImageUploader field;
        private FileUpload fileUpload;
        private Literal lblDispForm;
        private RegularExpressionValidator oPictureValidator;
        private HtmlTable table;

        public ImageUploaderControl(ImageUploader parentField)
        {
            this.field = parentField;
        }

        private string _uploadDocument(string theFile)
        {
            string str4;
            SPSite site = new SPSite(SPContext.Current.Web.Url);
            SPWeb web = site.OpenWeb();
            SPUserToken userToken = site.SystemAccount.UserToken;
            this.DiableAttachments();
            using (SPSite site2 = new SPSite(web.Url, userToken))
            {
                using (SPWeb web2 = site2.OpenWeb())
                {
                    web2.AllowUnsafeUpdates = true;
                    SPList typeToTarget = web2.Lists[this.field.MyCustomProperty];
                    string str = this.Url(typeToTarget);
                    Stream inputStream = this.fileUpload.PostedFile.InputStream;
                    byte[] buffer = new byte[inputStream.Length];
                    inputStream.Read(buffer, 0, (int)inputStream.Length);
                    inputStream.Close();
                    string extension = Path.GetExtension(this.fileUpload.FileName);
                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.fileUpload.FileName);
                    SPFile file = typeToTarget.RootFolder.Files.Add(fileNameWithoutExtension + "_main" + extension, buffer, true);
                    byte[] buffer2 = this.ImageResize(file.OpenBinary(), 100);
                    if (this.field.PAWidth != string.Empty)
                    {
                        buffer2 = this.ImageResize(file.OpenBinary(), Convert.ToInt32(this.field.PAWidth));
                    }
                    else
                    {
                        buffer2 = this.ImageResize(file.OpenBinary(), 100);
                    }
                    SPFile file2 = typeToTarget.RootFolder.Files.Add(fileNameWithoutExtension + "_thumb_" + this.field.PAWidth + extension, buffer2, true);
                    str = str.Replace("Forms", "").Replace(" ", "%20");
                    str4 = str + fileNameWithoutExtension + "_thumb_" + this.field.PAWidth + extension;
                }
            }
            return str4;
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            this.table = new HtmlTable();
            HtmlTableRow row = new HtmlTableRow();
            this.table.Rows.Add(row);
            HtmlTableRow row2 = new HtmlTableRow();
            this.table.Rows.Add(row2);
            HtmlTableCell cell = null;
            if ((base.ControlMode == SPControlMode.Edit) || (base.ControlMode == SPControlMode.New))
            {
                cell = new HtmlTableCell
                {
                    ColSpan = 2
                };
                cell.Attributes["class"] = "ms-formdescription";
                cell.InnerText = "Please pick your image:";
                row.Cells.Add(cell);
                row = new HtmlTableRow();
                cell = new HtmlTableCell();
                this.fileUpload = new FileUpload();
                this.fileUpload.ID = "fileUpload";
                this.oPictureValidator = new RegularExpressionValidator();
                this.oPictureValidator.ErrorMessage = "Only picture files are allowed!";
                this.oPictureValidator.ValidationExpression = @"^.+\.(([jJ][pP][eE]?[gG])|([gG][iI][fF]))$";
                this.oPictureValidator.ControlToValidate = "fileUpload";
                string itemFieldValue = (string)this.ItemFieldValue;
                cell.Controls.Add(this.fileUpload);
                cell.Controls.Add(this.oPictureValidator);
                row.Cells.Add(cell);
                this.table.Rows.Add(row);
            }
            cell = new HtmlTableCell();
            LiteralControl control = new LiteralControl();
            string str2 = "";
            object obj2 = new object();
            if (this.ItemFieldValue != null)
            {
                obj2 = this.ItemFieldValue;
            }
            if (obj2 != null)
            {
                str2 = Convert.ToString(obj2);
            }
            base.Controls.Add(this.table);
        }

        public void DiableAttachments()
        {
            base.List.EnableAttachments = false;
        }

        private byte[] ImageResize(byte[] byteArray, int targetSize)
        {
            int num;
            int num2;
            System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(byteArray));
            if (image.Height > image.Width)
            {
                num = targetSize;
                num2 = (int)(image.Width * (((float)targetSize) / ((float)image.Height)));
            }
            else
            {
                num2 = targetSize;
                num = (int)(image.Height * (((float)targetSize) / ((float)image.Width)));
            }
            System.Drawing.Image image2 = System.Drawing.Image.FromStream(new MemoryStream(byteArray));
            Bitmap bitmap = new Bitmap(num2, num, PixelFormat.Format24bppRgb);
            bitmap.SetResolution(72f, 72f);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.DrawImage(image2, new Rectangle(0, 0, num2, num), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Jpeg);
            image.Dispose();
            image2.Dispose();
            bitmap.Dispose();
            graphics.Dispose();
            return stream.GetBuffer();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void Render(HtmlTextWriter output)
        {
            base.Render(output);
        }

        public override void UpdateFieldValueInItem()
        {
            this.EnsureChildControls();
            try
            {
                if ((this.fileUpload.PostedFile != null) && (this.fileUpload.PostedFile.FileName != string.Empty))
                {
                    this.Value = this._uploadDocument(this.fileUpload.PostedFile.FileName);
                    this.ItemFieldValue = this.Value;
                }
            }
            catch (Exception)
            {
            }
        }

        public string Url(SPList typeToTarget)
        {
            string defaultViewUrl = typeToTarget.DefaultViewUrl;
            if (typeToTarget is SPDocumentLibrary)
            {
                int num = defaultViewUrl.IndexOf("Forms") + 6;
                defaultViewUrl = defaultViewUrl.Remove(num);
                if (defaultViewUrl.EndsWith("/"))
                {
                    defaultViewUrl = defaultViewUrl.Remove(defaultViewUrl.LastIndexOf("/"));
                }
                return defaultViewUrl;
            }
            int startIndex = defaultViewUrl.LastIndexOf("/");
            return defaultViewUrl.Remove(startIndex);
        }
    }
}
